package com.mayi.crm.interceptors;

import com.mayi.crm.exceptions.NoLoginException;
import com.mayi.crm.service.UserService;
import com.mayi.crm.utils.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yacong_liu
 * @version 1.0
 * @classname NoLoginInterceptor
 * @description
 * @date 2021/1/14
 **/
public class NoLoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserService userService;


    /**
     * 判断用户是否是登录状态，获取Cookie对象，解析用户ID值
     * 如果用户ID不为空，且数据库中存在对应用户记录，表示请求合法
     * 否则，请求不合法，进行拦截并重定向到登录页面
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取用户ID
        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);
        //2. 判断用户ID是否不为空且数据库中存在对应用户记录
        if (null == userId || null == userService.selectByPrimaryKey(userId)) {
            // 3. 抛出未登录异常
            throw new NoLoginException();
        }
        return true;
    }
}
